package org.example.utils;

import org.example.entity.CasUser;
import org.jasig.cas.client.validation.Assertion;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public final class CasUserUtils {

    private CasUserUtils() {}

    public static final String CAS_ASSERTION = "_const_cas_assertion_";

    // 获取Assertion
    public static Assertion getAssertion(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(CAS_ASSERTION);
        return attribute instanceof Assertion ? (Assertion) attribute : null;
    }

    // 获取用户名
    public static String getUsername(HttpServletRequest request) {
        Assertion assertion = getAssertion(request);
        return assertion != null ? assertion.getPrincipal().getName() : null;
    }

    // 获取特定属性
    public static Object getAttribute(HttpServletRequest request, String attrName) {
        Assertion assertion = getAssertion(request);
        if (assertion != null) {
            Map<String, Object> attrs = assertion.getPrincipal().getAttributes();
            return attrs != null ? attrs.get(attrName) : null;
        }
        return null;
    }

    /**
     * 获取CasUser用户对象
     * @param request
     * @return
     */
    public static CasUser getCasUser(HttpServletRequest request) {
        CasUser casUser = new CasUser();
        casUser.setId(getAttribute(request, "id").toString());
        casUser.setName(getAttribute(request, "name").toString());
        casUser.setOfficeId(getAttribute(request, "officeId").toString());
        casUser.setPhone(getAttribute(request, "phone").toString());
        casUser.setMobile(getAttribute(request, "mobile").toString());
        casUser.setUserType(getAttribute(request, "userType").toString());
        casUser.setEmail(getAttribute(request, "email").toString());
        return casUser;
    }
}
